package com.yql.commonextend.middleware.oss;

import com.aliyun.oss.OSSClient;
import com.yql.commonextend.config.OssConfig;
import com.yql.commonextend.exception.OssException;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云存储
 */
public class AliyunCloudStorageService extends CloudStorageService
{
    private OSSClient client;

    public AliyunCloudStorageService()
    {

        init();
    }

    private void init()
    {
        client = new OSSClient(OssConfig.getAliyunEndPoint(), OssConfig.getAliyunAccessKeyId(),
                OssConfig.getAliyunAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path)
    {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path)
    {
        try
        {
            client.putObject(OssConfig.getAliyunBucketName(), path, inputStream);
        }
        catch (Exception e)
        {
            throw new OssException("上传文件失败，请检查配置信息");
        }
        return OssConfig.getAliyunDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix)
    {
        return upload(data, getPath(OssConfig.getAliyunPrefix(), suffix));
    }

    @Override
    public String uploadPrefix(byte[] data, String prefix, String suffix) {
        return upload(data, getPath(OssConfig.getAliyunPrefix()+prefix, suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix)
    {
        return upload(inputStream, getPath(OssConfig.getAliyunPrefix(), suffix));
    }
}
